package com.enterprise.support.utility;

import org.w3c.dom.Document;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 11-10-23
 * Time: 上午11:28
 * To change this template use File | Settings | File Templates.
 */
public class SqlUtility {
    /*Sql键值对*/
    private final static Enterprise<Class, Enterprise<String, String>> cache = new Enterprise();
    private final static boolean devMode = Configuration.get().getBoolean("system.devmode");

    private final static String jdbcDriver = Configuration.getProperties("/config/jdbc.properties").getProperty("dbpool.driverClass");
    public final static Integer KEY_ORACLE = 1;
    public final static Integer KEY_H2 = 2;

    public static int getDbType() {
        if (jdbcDriver.matches(".+OracleDriver")) {
            return 1;
        } else if (jdbcDriver.matches("org.h2.Driver")) {
            return 2;
        } else {
            return 0;
        }
    }

    public static String getCurrentDate() {
        switch (getDbType()) {
            case 1:
                return "sysdate";
            case 2:
                return "now()";
        }
        return "data";
    }


    /**
     * 读取Sql语句
     */
    public static synchronized String getQueryString(Class claz, String postfix) {
        Enterprise queryStrings = cache.get(claz);
        if (null == queryStrings) {
            cache.put(claz, queryStrings = new Enterprise());
        }
        if (queryStrings.isEmpty() || devMode) {
            try {
                String filepath = Configuration.ConfHomeDirectory + "/classes/" + claz.getName().replace(".", File.separator) + ".xml";
                String content = FileUtility.readStream(new FileInputStream(filepath));
                Document document = FileUtility.parseDocumentByString(content);
                String sqlCount = FileUtility.xpath("count(//key)", document);
                for (int i = 1; i < Integer.valueOf(sqlCount) + 1; i++) {
                    String key = FileUtility.xpath("//sql/key[" + i + "]/@name", document);
                    String body = FileUtility.xpath("//sql/key[" + i + "]/text()", document);
                    queryStrings.put(key, body);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return queryStrings.getString(postfix);
    }

    public static void main(String[] args) {
        System.out.println(SqlUtility.class.getPackage());
    }
}
